/*
 * MasterBot.cpp
 *
 *  Created on: Nov 18, 2008
 *      Author: nathan
 */

#include "MasterBot.h"

MasterBot::MasterBot(QObject* parent)
	: QObject(parent)
{
}

QString MasterBot::getLastError(void)
{
	return this->lastError;
}

bool MasterBot::registerBncsBot(ServiceAddress server)
{
  return false;
}

/*
bool MasterBot::registerServer(QString host, quint16 port)
{
	QString sn = QString("%1:%2").arg(host).arg(port);

	if (bncs_table.contains(sn))
	{
		this->lastError = tr("server already registered");
		return false;
	}

	BnetServerInfo* server = new BnetServerInfo();
	server->host = host;
	server->port = port;

	bncs_table.insert(sn, server);

	return true;
}

bool MasterBot::registerChannelBot(QString host, quint16 port, QString channel, QString user, QString pass)
{
	QString sn = QString("%1:%2").arg(host).arg(port);
	if (!bncs_table.contains(sn))
	{
		this->lastError = tr("server not registered");
		return false;
	}

	// Get the server object.
	BnetServerInfo* server = bncs_table.value(sn);

	// Create a new chat client and connect it.
	BncsClient* client = new BncsClient(this);
	connect(client, SIGNAL(loginStarted(BncsClient*)),
	        this, SLOT(onBncsLoginStarted(BncsClient*)));
	connect(client, SIGNAL(loginAborted(BncsClient*, QString)),
	        this, SLOT(onBncsLoginAborted(BncsClient*, QString)));
	connect(client, SIGNAL(loginComplete(BncsClient*)),
	        this, SLOT(onBncsLoginComplete(BncsClient*)));

	connect(client, SIGNAL(chatJoin(BncsClient*, QString, QStringList, bool)),
	        this, SLOT(onBncsJoin(BncsClient*, QString, QStringList, bool)));

	connect(client, SIGNAL(chatTalk(BncsClient*, QString, QString)),
	        this, SLOT(onBncsChat(BncsClient*, QString, QString)));
	connect(client, SIGNAL(chatWhisper(BncsClient*, QString, QString)),
	        this, SLOT(onBncsChat(BncsClient*, QString, QString)));

	// Create a new client info for this chat bot.
	BnetClientInfo* ci = new BnetClientInfo();
	ci->server = server;
	ci->client = client;
	ci->channel = channel;

	// Set the client context so we can get a reference
	// to this client when a signal comes in.
	client->setContext(ci);

	// Insert this bot into the server's chat bot list.
	server->chat_bots.insert(user, ci);

	/// Start the chat bot.
	client->startLogin(server->host, server->port, user, pass);

	return true;
}

bool MasterBot::registerGameBot(QString host, quint16 port, QString user, QString pass)
{
	return false;
}

void MasterBot::onBncsLoginStarted(BncsClient* client)
{
	QTextStream out (stdout);

	out << QString("Login started for user %1 on %2:%3.")
	       .arg(client->getUser()).arg(client->getHost()).arg(client->getPort())
	    << endl;
}

void MasterBot::onBncsLoginAborted(BncsClient* client, QString reason)
{
	QTextStream out (stdout);

	out << QString("Login failed for user %1 on %2:%3.  Reason: %4.")
		   .arg(client->getUser()).arg(client->getHost()).arg(client->getPort())
		   .arg(reason)
	    << endl;

	// TODO: cleanup
}

void MasterBot::onBncsLoginComplete(BncsClient* client)
{
	QTextStream out (stdout);

	out << QString("Login succeeded for user %1 on %2:%3.")
		   .arg(client->getUser()).arg(client->getHost()).arg(client->getPort())
		<< endl;

	BnetClientInfo* ci = (BnetClientInfo*)client->getContext();

	client->joinChannel(ci->channel);
}

void MasterBot::onBncsJoin(BncsClient* client, QString user, QStringList flags, bool existing)
{
	QTextStream out(stdout);

	out << QString("%1@%2:%3 has joined the channel.").arg(user).arg(client->getHost()).arg(client->getPort())
	    << endl;

	if (!existing)
	{
	  // Send a welcome message!
		QString greeting;
		int hour = QTime::currentTime().hour();
		if (hour >= 3 && hour < 12)
		{
			greeting = "Good morning";
		}
		else if (hour >= 12 && hour < 18)
		{
			greeting = "Good afternoon";
		}
		else // (hour >= 18 || hour < 3)
		{
			greeting = "Good evening";
		}

		QString chan = ((BnetClientInfo*)client->getContext())->channel;

		client->sendWhisper(QString("%1, %2!  Welcome to channel %3!  The current local time is %4.").arg(greeting).arg(user).arg(chan).arg(QTime::currentTime().toString(Qt::DefaultLocaleShortDate)), user);
	}
}

void MasterBot::onBncsChat(BncsClient* client, QString user, QString text)
{
	QTextStream out(stdout);

	out << QString("%1@%2:%3: %4").arg(user).arg(client->getHost()).arg(client->getPort()).arg(text)
	    << endl;

	// Check if we received a command!
	do
	{
		if (!text.startsWith("."))
		{
			break;
		}

		text.remove(0, 1); //Remove the trigger

		// Parse the command string.
		QStringList argv = text.split(' ', QString::SkipEmptyParts);
		if (argv.size() == 0)
		{
			break;
		}

		QString cmd = argv[0];
		if (!cmd[0].isLetter())
		{
			break;
		}

		if (cmd.compare("say", Qt::CaseInsensitive) == 0)
		{
			QString response;
			for (int i = 1; i < argv.size(); i++)
			{
				response += argv[i] + " ";
			}
			response = response.trimmed();

			client->sendChat(response);
		}
		else if (cmd.compare("version", Qt::CaseInsensitive) == 0)
		{
			client->sendWhisper("Curious, aren't we?", user);
		}
		else if (cmd.compare("wersion", Qt::CaseInsensitive) == 0)
		{
			client->sendWhisper("xaxaxaxa", user);
		}
		else if (cmd.compare("fortune", Qt::CaseInsensitive) == 0)
		{
			QProcess fortune_proc;

			// Get a short fortune
			fortune_proc.start("/usr/games/fortune", QStringList() << "-s");

			if (!fortune_proc.waitForStarted(1000))
			{
				client->sendChat("Could not start /usr/games/fortune.");
				break;
			}

			fortune_proc.closeWriteChannel();

			if (!fortune_proc.waitForFinished(2000))
			{
				client->sendChat("Timeout while waiting for /usr/games/fortune.");
				break;
			}

			QString fortune = fortune_proc.readAll();
			fortune.replace(QRegExp("\\s+"), " ");
			fortune = fortune.trimmed();
			client->sendChat(fortune);
		}
		else
		{
			client->sendWhisper(QString("I don't know the command \"%1\".").arg(cmd), user);
		}
	} while (false);
}

*/
